from typing import List, Optional
from fastapi import APIRouter, HTTPException, status, Depends
from pydantic import BaseModel
from database import get_db

router = APIRouter(
    prefix="/customers",
    tags=["customers"],
)


class CustomerBase(BaseModel):
    customerName: str
    PID: str
    telephone: str
    address: str


class CustomerCreate(CustomerBase):
    password: str


class CustomerUpdate(BaseModel):
    customerName: Optional[str] = None
    PID: Optional[str] = None
    telephone: Optional[str] = None
    address: Optional[str] = None
    password: Optional[str] = None


class Customer(CustomerBase):
    customerID: int


@router.post("/", status_code=status.HTTP_201_CREATED)
def add_customer(customer: CustomerCreate, conn=Depends(get_db)):
    try:
        cursor = conn.cursor()
        args = [
            customer.customerName,
            customer.PID,
            customer.telephone,
            customer.address,
            customer.password,
            0,  # p_new_customerID 的占位符
        ]
        result_args = cursor.callproc("sp_AddCustomer", args)
        conn.commit()
        new_customer_id = result_args[5]

        return {
            "customerID": new_customer_id,
            "message": "Customer added successfully.",
        }
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    finally:
        cursor.close()


@router.delete("/{customer_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_customer(customer_id: int, conn=Depends(get_db)):
    try:
        cursor = conn.cursor()
        cursor.callproc("sp_DeleteCustomer", (customer_id,))
        conn.commit()
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    finally:
        cursor.close()


@router.put("/{customer_id}")
def update_customer(customer_id: int, customer: CustomerUpdate, conn=Depends(get_db)):
    try:
        cursor = conn.cursor()
        cursor.callproc(
            "sp_UpdateCustomer",
            (
                customer_id,
                customer.customerName,
                customer.PID,
                customer.telephone,
                customer.address,
                customer.password,
            ),
        )
        conn.commit()
        return {"message": "Customer updated successfully."}
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    finally:
        cursor.close()


@router.get("/{customer_id}")
def get_customer_by_id(customer_id: int, conn=Depends(get_db)):
    try:
        cursor = conn.cursor(dictionary=True)
        cursor.callproc("sp_GetCustomerById", (customer_id,))
        for result in cursor.stored_results():
            customer = result.fetchone()
        if customer:
            return customer
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Customer not found"
        )
    finally:
        cursor.close()


@router.get("/search/")
def search_customers(keyword: str, conn=Depends(get_db)):
    try:
        cursor = conn.cursor(dictionary=True)
        cursor.callproc("sp_SearchCustomers", (keyword,))
        for result in cursor.stored_results():
            customers = result.fetchall()
        return customers
    finally:
        cursor.close()


@router.get("/")
def get_all_customers(conn=Depends(get_db)):
    try:
        cursor = conn.cursor(dictionary=True)
        cursor.callproc("sp_GetAllCustomers")
        for result in cursor.stored_results():
            customers = result.fetchall()
        return customers
    finally:
        cursor.close()
